import React, { Component } from 'react';
import { connect } from 'dva';
import { routerRedux, Link } from 'dva/router';
import path from 'path';
import moment from 'moment';
import { RIGHTS } from '../../constants';
import { Form, Input, Tabs, Button, Icon, Checkbox, Row, Col, Alert, message, Upload, Table, Card, Modal } from 'antd';
import { QINIU_DOMAIN, QINIU_UPLOAD_DOMAIN } from '../../constants';
import { queryUserBySms, setUserPhone } from '../../services/user';
import styles from './UserInfo.less';

const FormItem = Form.Item;
const { TabPane } = Tabs;

@connect(state => ({
  currentUser: state.user.currentUser,
  qiniucloud: state.qiniucloud,
  team: state.user.team,
}))
@Form.create()

export default class UserInfo extends Component {
  state = {
    currentUser: {
      name: '',
      nickname: '',
      avatar: '',
      phone: '',
    },
    users: [{}],
    nameChanged: false,
    nicknameChanged: false,
    invitation_code: '',
    visible: false,
    loading: false,
    sms_code: '',
    count: 0,
  }
  componentDidMount() {
    this.handleFetchCurrentUser();
    this.props.dispatch({
      type: 'qiniucloud/fetchUptoken'
    });
  }
  componentWillReceiveProps(nextProps) {
    const { dispatch } = this.props;

  }

  handleFetchCurrentUser = () => {
    this.props.dispatch({
      type: 'user/fetchCurrent',
      callback: (result) => {
        this.setState({
          currentUser: result.user,
          users: result.users,
        });
      },
    });
  }
  handleChangeAvatar = async ({ file }) => {
    const { dispatch, currentUser } = this.props;
    if (file.response && !file.error) {
      const url = `${QINIU_DOMAIN}/${file.response.key}`;
      dispatch({
        type: 'user/update',
        payload: {
          _id: currentUser._id,
          avatar: url,
        },
        callback: (result) => {
          if (result.error) {
            message.error(result.msg);
          } else {
            message.success(result.msg);
            this.setState({
              currentUser: { ...this.state.currentUser, avatar: url }
            })
          }
        },
      });
    }
  }
  makeUploadData = (file) => {
    const { qiniucloud } = this.props;
    const extname = path.extname(file.name);
    return {
      token: qiniucloud.uptoken,
      key: `${file.uid}${extname}`,
    }
  }
  handleSubmit = (field) => {
    const { dispatch } = this.props;
    const { currentUser } = this.state;
    if (field === 'name' && !currentUser.name) {
      message.warn('姓名不能为空');
    } else if (field === 'nickname' && !currentUser.nickname) {
      message.warn('昵称不能为空');
    } else {
      dispatch({
        type: 'user/update',
        payload: {
          _id: currentUser._id,
          [field]: currentUser[field],
        },
        callback: (result) => {
          if (result.error) {
            message.error(result.msg);
          } else {
            message.success(result.msg);
          }
          this.setState({
            [`${field}Changed`]: false,
          });
        },
      });
    }
  }
  handleJoinTeam = () => {
    const { dispatch, currentUser } = this.props;
    dispatch({
      type: 'user/joinTeam',
      payload: {
        user_id: currentUser._id,
        invitation_code: this.state.invitation_code,
      },
      callback: (result) => {
        if (result.error) {
          message.error(result.msg);
        } else {
          this.handleFetchCurrentUser();
          message.success(result.msg);
        }
      },
    });
  }
  handleSms = () => {
    this.setState({
      visible: true,
      loading: false
    })
  }
  handleCancel = () => {
    this.setState({
      visible: false,
    });
  }
  handleOk = (e) => {
    const { currentUser } = this.state;
    this.props.form.validateFields({ force: true },
      async (err, values) => {
        if (!err) {
          this.setState({ sms_code: values.sms_code });
          const result = await setUserPhone({ sms: values.sms_code, phone: currentUser.phone, _id: currentUser._id });

          if (result.error) {
            message.error(result.msg)
          } else {
            this.setState({
              loading: true,
              visible: false
            })
            message.success(result.msg)
          }
        }
      }
    )
  }
  componentWillUnmount() {
    clearInterval(this.interval);
  }
  onGetCaptcha = () => {
    this.props.dispatch({
      type: `login/getSmsCode`,
      payload: {
        phone: this.state.currentUser.phone
      },
    });
    let count = 59;
    this.setState({ count });
    this.interval = setInterval(() => {
      count -= 1;
      this.setState({ count });
      if (count === 0) {
        clearInterval(this.interval);
      }
    }, 1000);
  }
  render() {
    const { currentUser, users, visible, count, sms_code, loading } = this.state;
    const { team, form } = this.props;
    const { getFieldDecorator, register } = form;
    const columns = [{
      title: '姓名',
      dataIndex: 'name',
      key: 'name'
    }, {
      title: '昵称',
      dataIndex: 'nickname',
      key: 'nickname'
    }, {
      title: '权限',
      dataIndex: 'rights',
      key: 'rights',
      render(val) {
        if (val) {
          const rights = [];
          val.forEach(item => {
            const right = RIGHTS.find(item1 => item1.value === item);
            if (right) rights.push(right.label);
          });
          return rights.join(',');
        }
        return '';
      },
    }, {
      title: '等级',
      dataIndex: 'writer_level',
      key: 'writer_level',
      render: (val) => {
        return val !== undefined ? `P${val}` : ''
      }
    }, {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'creare_time',
      render: (val) => {
        return moment(val).fromNow()
      }
    }, {
      title: '最近登录',
      dataIndex: 'last_login_time',
      key: 'last_login_time',
      render: (val) => {
        return moment(val).fromNow()
      }
    }]
    return (
      <div className={styles.main}>
        <div className={styles.top}>
          个人信息
        </div>
        <div>
          <Row className={styles.rowBox}>
            <Col className={styles.labelSpan} span={6}>
              <span>头像：</span>
            </Col>
            <Col span={14}>
              {currentUser.avatar &&
                <img className={styles.imgBox} src={currentUser.avatar} />
              }
            </Col>
            <Col span={4} style={{ textAlign: 'right' }}>
              <div type="primary" style={{ height: 80, lineHeight: '80px' }}>
                <Upload
                  name="file"
                  listType="text"
                  showUploadList={false}
                  action={QINIU_UPLOAD_DOMAIN}
                  data={this.makeUploadData}
                  onChange={this.handleChangeAvatar}
                  style={{ color: '#40a9ff', cursor: 'pointer' }}
                >
                  修改
                </Upload>
              </div>
            </Col>
          </Row>
          <Row className={styles.rowBox}>
            <Col className={styles.labelSpan} span={6}>
              <span>姓名：</span>
            </Col>
            <Col span={14}>
              <Input
                className={styles.userInput}
                placeholder="最多10字"
                maxLength="10"
                value={currentUser.name}
                onChange={(e) => this.setState({ currentUser: { ...currentUser, name: e.target.value.trim() }, nameChanged: true })}
              />
            </Col>
            <Col span={4} style={{ textAlign: 'right' }}>
              <Button type="primary" onClick={() => this.handleSubmit('name')} disabled={!this.state.nameChanged}>保存</Button>
            </Col>
          </Row>
          <Row className={styles.rowBox}>
            <Col className={styles.labelSpan} span={6}>
              <span>昵称：</span>
            </Col>
            <Col span={14}>
              <Input
                className={styles.userInput}
                placeholder="最多10字"
                maxLength="10"
                value={currentUser.nickname}
                onChange={(e) => this.setState({ currentUser: { ...currentUser, nickname: e.target.value.trim() }, nicknameChanged: true })}
              />
            </Col>
            <Col span={4} style={{ textAlign: 'right' }}>
              <Button type="primary" onClick={() => this.handleSubmit('nickname')} disabled={!this.state.nicknameChanged}>保存</Button>
            </Col>
          </Row>
          <Row className={styles.rowBox}>
            <Col className={styles.labelSpan} span={6}>
              <span>手机号：</span>
            </Col>
            <Col span={15}>
              <span>{currentUser.phone}</span>
            </Col>
            <Col style={{ textAlign: 'right' }}>
              <Button onClick={this.handleSms}>更换</Button>
            </Col>
          </Row>
          <Modal
            title='更换手机号'
            visible={visible}
            onCancel={this.handleCancel}
            footer={null}
            bodyStyle={{ textAlign: 'center' }}
          >
            <Input
              style={{ width: 210 }}
              maxLength="11"
              value={currentUser.phone}
              onChange={(e) => this.setState({ currentUser: { ...currentUser, phone: e.target.value.trim() } })}
            />
            <Form>
              <FormItem>
                {getFieldDecorator('sms_code', {
                  rules: [{
                    required: true, message: '请输入验证码！',
                  }],
                })(
                  <Input style={{ width: 100, marginTop: 10 }}
                    placeholder="输入验证码"
                  />
                )}
                <Button
                  disabled={count}
                  onClick={this.onGetCaptcha}
                  style={{ marginLeft: 10, width: 100 }}
                >
                  {count ? `${count} s` : '获取验证码'}
                </Button>
              </FormItem>
              <Button onClick={this.handleOk} type="primary" loading={this.state.loading} htmlType="submit">
                确定更改
              </Button>
            </Form>
          </Modal>
          <Row className={styles.rowBox}>
            <Col className={styles.labelSpan} span={6}>
              <span>淘宝账号：</span>
            </Col>
            <Col span={18}>
              {currentUser.taobao &&
                <span>{currentUser.taobao.taobao_user_nick}</span>
              }
            </Col>
          </Row>
          <Row className={styles.rowBox}>
            <Col className={styles.labelSpan} span={6}>
              <span>所属团队：</span>
            </Col>
            {team && team.name &&
              <Col span={18}>
                <span>{team.name}</span>
              </Col>
            }
            {!(team && team.name) &&
              <Col span={14}>
                <Input
                  className={styles.userInput}
                  placeholder="请输入邀请码"
                  value={this.state.invitation_code}
                  onChange={(e) => this.setState({ invitation_code: e.target.value })}
                />
              </Col>
            }
            {!(team && team.name) &&
              <Col span={4} style={{ textAlign: 'right' }}>
                <Button type="primary" onClick={() => this.handleJoinTeam()}>加入</Button>
              </Col>
            }
          </Row>
          <Row className={styles.rowBox}>
            <Col className={styles.labelSpan} span={6}>
              <span>关联账户：</span>
            </Col>
            {users ?
              <Card>
                <Table
                  columns={columns}
                  dataSource={users}
                  rowKey="_id"
                />
              </Card>
              : ''}
          </Row>
          <div style={{ textAlign: 'center', paddingTop: 20 }}>
            <Link to="/">
              <Button style={{ width: 100 }}>返回</Button>
            </Link>
          </div>
        </div>
      </div>
    );
  }
}
